<template>
  <!-- 剩余发票统计 -->
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsData"
          :formData="form"
        >
          <template #queryNo="{ input, value }">
            <VBatchInput
              @update:model-value="input"
              :model-value="value"
              placeholder="请输入"
              class="w-60"
              @search="refresh"
            />
          </template>
          <template #supplier="{ input, value }">
            <el-select-v2
              :model-value="value"
              @update:model-value="input"
              :options="supplieList || []"
              placeholder="请选择供应商"
              multiple
              filterable
              clearable
              collapse-tags
              collapse-tags-tooltip
              style="min-width: 200px"
            />
          </template>
          <template #invoiceNum="{ input, value }">
            <NumberRangeSea
              :model-value="value"
              @update:model-value="input"
              placeholder="未配票数量"
              checkValue
            />
          </template>
          <template #remainNum="{ input, value }">
            <NumberRangeSea
              :model-value="value"
              @update:model-value="input"
              placeholder="剩余发票数量"
              checkValue
            />
          </template>
          <template #processNums="{ input, value }">
            <NumberRangeSea
              :model-value="value"
              @update:model-value="input"
              placeholder="待处理发票数量"
              checkValue
            />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions" />
      </template>
      <template #operation="{ row }">
        <div>
          <el-button
            link
            type="primary"
            @click="handleDeal(row)"
            v-hasPermi="[exportRebatesAuthList.residual_invoice.deal]"
          >
            处理
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleCancel(row)"
            v-hasPermi="[exportRebatesAuthList.residual_invoice.cancel]"
          >
            作废
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleLog(row)"
            v-hasPermi="[exportRebatesAuthList.residual_invoice.log]"
          >
            日志
          </el-button>
        </div>
      </template>
    </VTable>
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <Log
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="out.statistic-remain-invoice"
      :business_id="logId"
      @close="logId = null"
    />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import Log from "@/components/Log/index.vue";
import XForm from "@/components/XForm/index.vue";
import { exportRebatesAuthList } from "@/Auth/export-rebates.js";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import { config_name } from "@/config/export.js";
import { useEnumSelect } from "@/hooks";
import { getTableSelectRow, tipMessage } from "@/hooks/tool.js";
import { invoiceList, invoiceCancel } from "./api/index.js";
import { getSupplie } from "@/api/public.js";
import NumberRangeSea from "@/components/NumberRangeSea/index.vue";
import VBatchInput from '@/componentsPublic/BatchInput/index.vue'
const { proxy } = getCurrentInstance();
const { options: optionsData } = useEnumSelect({
  params: ["out_return_tax_status", "out_ri_is_handle"],
});
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      numberNo: "",
      return_tax_status: "",
      sku: "",
      dateRange: { type: "return_tax_apply_time", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    {
      fixed: "left",
      title: "下单主体",
      width: 230,
      field: "order_main_company_name",
    },
    {
      title: "采购下单时间",
      fixed: "left",
      width: 200,
      field: "purchase_order_time",
    },
    { title: "供应商代码", width: 160, field: "supplier_code" },
    { title: "部门", width: 260, field: "department_name" },
    { title: "PO", width: 160, field: "purchase_number" },
    { title: "SKU", width: 160, field: "sku" },
    { title: "下单数量", width: 120, field: "pms_purchase_num" },
    { title: "入库数量", width: 120, field: "pms_inbound_num" },
    { title: "不良品数量", width: 120, field: "pms_reject_num" },
    { title: "取消下单数量", width: 120, field: "pms_cancel_num" },
    { title: "报损数量", width: 120, field: "pms_damage_num" },
    { title: "库内退货数量", width: 120, field: "pms_actual_return_num" },
    { title: "发票代码", width: 160, field: "invoice_code" },
    { title: "发票号码", width: 160, field: "invoice_number" },
    { title: "开票品名", width: 160, field: "invoice_billing_name" },
    { title: "开票单位", width: 160, field: "invoice_billing_unit" },
    { title: "发票数量", width: 120, field: "invoice_nums" },
    { title: "发票不含税单价", width: 160, field: "invoice_ex_tax_price" },
    { title: "发票不含税金额", width: 160, field: "invoice_ex_tax_amount" },
    { title: "发票税额", width: 160, field: "invoice_tax_amount" },
    { title: "发票行号", width: 160, field: "invoice_row_no" },
    { title: "税点", width: 160, field: "invoice_tax_point" },
    { title: "已配票数量", width: 120, field: "invoice_al_nums" },
    { title: "未配票数量", width: 120, field: "invoice_un_nums" },
    {
      title: "未配票不含税金额",
      width: 160,
      field: "invoice_un_ex_tax_amount",
    },
    { title: "未配票税额", width: 160, field: "invoice_un_tax_amount" },
    { title: "开票数量", width: 120, field: "invoice_billing_nums" },
    { title: "报关数量", width: 120, field: "pre_declare_num" },
    { title: "出库数量", width: 120, field: "pms_outbound_num" },
    { title: "剩余库存数量", width: 120, field: "pms_leave_num" },
    {
      title: "剩余未开票数量",
      width: 120,
      field: "invoice_billing_remain_nums",
    },
    { title: "剩余发票数量", width: 120, field: "invoice_remain_nums" },
    {
      title: "待处理发票数量",
      width: 120,
      field: "invoice_billing_process_nums",
    },
    { title: "是否处理", width: 90, field: "is_handle_text" },
    { title: "处理日期", width: 170, field: "handle_time" },
    { title: "备注", width: 200, field: "remark" },
    {
      title: "操作",
      field: "",
      fixed: "right",
      width: 150,
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return invoiceList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const refresh = () => {
  tableRef?.value.query()
};
const logId = ref(null);
const logVisible = ref(false);
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};
//导出中心
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["export_rebates"]["statistic_remain_invoice"],
    condition,
  });
};
const handleimport = () => {};
const handleDeal = () => {
  ElMessage.warning("TODO,功能待定!");
};
const handleCancel = (row) => {
  handleCancelReq([row.purchase_invoice_id]);
};
const handleBatchCancel = () => {
  let records = tableRef.value?.$table?.getCheckboxRecords() || [];
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  let rows = records?.map((item) => item.purchase_invoice_id);
  handleCancelReq(rows);
};
const handleCancelReq = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认废除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, data, message } = await invoiceCancel(id);
          if (code != 200) return ElMessage.error(message);
          tipMessage(data);
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

const supplieList = ref([]);
const getSupplieList = async () => {
  const { data } = await getSupplie();
  let list = data.map((item) => {
    return {
      label: item.supplier_name,
      value: item.supplier_code,
    };
  });
  supplieList.value = list || [];
};
getSupplieList();

const publicStyle = { style: { width: "300px" } };
const fieldList = [
  {
    field: "numberNo",
    placeholder: "请输入",
    slot: "queryNo",
    selectStyle: { width: "100px" },
    select: [
      { label: "采购单号", value: "purchase_number" },
      { label: "sku", value: "sku" },
      { label: "发票号码", value: "invoice_number" },
    ],
  },
  {
    field: "supplier_code",
    slot: "supplier",
    placeholder: "供应商",
  },
  {
    field: "invoice_un_nums",
    slot: "invoiceNum",
    placeholder: "未配票数量",
  },
  {
    field: "invoice_remain_nums",
    slot: "remainNum",
    placeholder: "剩余发票数量",
  },
  {
    field: "invoice_billing_process_nums",
    slot: "processNums",
    placeholder: "待处理发票数量",
  },
  {
    field: "return_tax_status",
    type: "select",
    originOption: "out_return_tax_status",
    options: {
      placeholder: "退税申报状态",
    },
    style: { width: "140px" },
  },
  {
    field: "sku",
    placeholder: "商品代码",
    type: "input",
    ...publicStyle,
  },
  {
    field: "dateRange",
    type: "dateTimeRange",
    style: { width: "360px" },
    selectStyle: { width: "150px" },
    select: [
      { label: "申请退税时间", value: "return_tax_apply_time" },
      { label: "退税款到账时间", value: "return_tax_amount_arrival_time" },
    ],
    itemProps: {
      startPlaceholder: "最早时间",
      endPlaceholder: "最晚时间",
    },
  },
];

const actions = [
  {
    label: "批量作废",
    fn: handleBatchCancel,
    type: "danger",
    permission: [exportRebatesAuthList.residual_invoice.cancel],
  },
  {
    label: "导出",
    dkicon: "icon-Upload",
    right: true,
    fn: handleExport,
    permission: [exportRebatesAuthList.residual_invoice.export],
  },
];
</script>

<style lang="scss" scoped></style>
